<!DOCTYPE html>
<!-- saved from url=(0049)http://mybatis.org/spring/zh/getting-started.html -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="Hunter Presnall">
    <meta name="author" content="Eduardo Macarron">
    <meta name="author" content="Nan Lei">
    <meta name="Date-Revision-yyyymmdd" content="20200309">
    <meta http-equiv="Content-Language" content="zh">
    <title>mybatis-spring – MyBatis-Spring | 入门</title>
    <link rel="stylesheet" href="./mybatis-spring – MyBatis-Spring _ 入门_files/apache-maven-fluido-1.7.min.css">
    <link rel="stylesheet" href="./mybatis-spring – MyBatis-Spring _ 入门_files/site.css">
    <link rel="stylesheet" href="./mybatis-spring – MyBatis-Spring _ 入门_files/print.css" media="print">
    <script type="text/javascript" src="./mybatis-spring – MyBatis-Spring _ 入门_files/apache-maven-fluido-1.7.min.js.下载"></script>
  </head>
  <body class="topBarDisabled">
    <div class="container-fluid">
      <div id="banner">
        <div class="pull-left"><div id="bannerLeft"><h2>mybatis-spring</h2>
</div>
</div>
        <div class="pull-right"><a href="http://mybatis.org/" id="bannerRight" title="MyBatis logo"><img src="./mybatis-spring – MyBatis-Spring _ 入门_files/mybatis-logo.png" alt="MyBatis logo"></a></div>
        <div class="clear"><hr></div>
      </div>

      <div id="breadcrumbs">
        <ul class="breadcrumb">
        <li id="publishDate">最近更新: 09 三月 2020<span class="divider">|</span>
</li>
          <li id="projectVersion">版本: 2.0.4</li>
        </ul>
      </div>
      <div class="row-fluid">
        <div id="leftColumn" class="span2">
          <div class="well sidebar-nav">
    <ul class="nav nav-list">
      <li class="nav-header">参考文档</li>
    <li><a href="http://mybatis.org/spring/zh/index.html" title="简介"><span class="none"></span>简介</a></li>
    <li class="active"><a href="http://mybatis.org/spring/zh/getting-started.html#"><span class="none"></span>入门</a></li>
    <li><a href="http://mybatis.org/spring/zh/factorybean.html" title="SqlSessionFactoryBean"><span class="none"></span>SqlSessionFactoryBean</a></li>
    <li><a href="http://mybatis.org/spring/zh/transactions.html" title="事务"><span class="icon-chevron-right"></span>事务</a></li>
    <li><a href="http://mybatis.org/spring/zh/sqlsession.html" title="使用 SqlSession"><span class="icon-chevron-right"></span>使用 SqlSession</a></li>
    <li><a href="http://mybatis.org/spring/zh/mappers.html" title="注入映射器"><span class="icon-chevron-right"></span>注入映射器</a></li>
    <li><a href="http://mybatis.org/spring/zh/boot.html" title="使用 Spring Boot"><span class="none"></span>使用 Spring Boot</a></li>
    <li><a href="http://mybatis.org/spring/zh/using-api.html" title="使用 MyBatis API"><span class="none"></span>使用 MyBatis API</a></li>
    <li><a href="http://mybatis.org/spring/zh/batch.html" title="使用 Spring Batch"><span class="none"></span>使用 Spring Batch</a></li>
    <li><a href="http://mybatis.org/spring/zh/sample.html" title="示例代码"><span class="none"></span>示例代码</a></li>
      <li class="nav-header">项目文档</li>
    <li><a href="http://mybatis.org/spring/zh/project-info.html" title="项目信息"><span class="icon-chevron-right"></span>项目信息</a></li>
    <li><a href="http://mybatis.org/spring/zh/project-reports.html" title="项目报表"><span class="icon-chevron-right"></span>项目报表</a></li>
</ul>
          <hr>
          <div id="poweredBy">
            <div class="clear"></div>
            <div class="clear"></div>
            <div class="clear"></div>
            <div class="clear"></div>
<a href="http://maven.apache.org/" title="构建依靠 Maven" class="poweredBy"><img class="builtBy" alt="构建依靠 Maven" src="./mybatis-spring – MyBatis-Spring _ 入门_files/maven-feather.png"></a>
            </div>
          </div>
        </div>
        <div id="bodyColumn" class="span10">


  
    <div class="section">
<h2><a name="a.E5.85.A5.E9.97.A8"></a>入门</h2>
      
<p>
      本章将会以简略的步骤告诉你如何安装和配置 MyBatis-Spring，并构建一个简单的具备事务管理功能的数据访问应用程序。
      </p>

    
<div class="section">
<h3><a name="a.E5.AE.89.E8.A3.85"></a>安装</h3>
      
<p>
      要使用 MyBatis-Spring 模块，只需要在类路径下包含 <tt>mybatis-spring-2.0.4.jar</tt> 文件和相关依赖即可。
      </p>
      
<p>
      如果使用 Maven 作为构建工具，仅需要在 pom.xml 中加入以下代码即可：
      </p>
        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;dependency&gt;</span><span class="pln">
  </span><span class="tag">&lt;groupId&gt;</span><span class="pln">org.mybatis</span><span class="tag">&lt;/groupId&gt;</span><span class="pln">
  </span><span class="tag">&lt;artifactId&gt;</span><span class="pln">mybatis-spring</span><span class="tag">&lt;/artifactId&gt;</span><span class="pln">
  </span><span class="tag">&lt;version&gt;</span><span class="pln">2.0.4</span><span class="tag">&lt;/version&gt;</span><span class="pln">
</span><span class="tag">&lt;/dependency&gt;</span></pre></div>
    </div>

    
<div class="section">
<h3><a name="a.E5.BF.AB.E9.80.9F.E4.B8.8A.E6.89.8B"></a>快速上手</h3>
      
<p>
      要和 Spring 一起使用 MyBatis，需要在 Spring 应用上下文中定义至少两样东西：一个 <tt>SqlSessionFactory</tt> 和至少一个数据映射器类。
      </p>

      
<p>
      在 MyBatis-Spring 中，可使用 <tt>SqlSessionFactoryBean</tt>来创建 <tt>SqlSessionFactory</tt>。
      要配置这个工厂 bean，只需要把下面代码放在 Spring 的 XML 配置文件中：
      </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"sqlSessionFactory"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.mybatis.spring.SqlSessionFactoryBean"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"dataSource"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"dataSource"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/bean&gt;</span></pre></div>

      
<div class="source"><pre class="prettyprint"><span class="lit">@Bean</span><span class="pln">
</span><span class="kwd">public</span><span class="pln"> </span><span class="typ">SqlSessionFactory</span><span class="pln"> sqlSessionFactory</span><span class="pun">()</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">SqlSessionFactoryBean</span><span class="pln"> factoryBean </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">SqlSessionFactoryBean</span><span class="pun">();</span><span class="pln">
  factoryBean</span><span class="pun">.</span><span class="pln">setDataSource</span><span class="pun">(</span><span class="pln">dataSource</span><span class="pun">());</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> factoryBean</span><span class="pun">.</span><span class="pln">getObject</span><span class="pun">();</span><span class="pln">
</span><span class="pun">}</span></pre></div>

      
<p>
      注意：<tt>SqlSessionFactory</tt> 需要一个 <tt>DataSource</tt>（数据源）。
      这可以是任意的 <tt>DataSource</tt>，只需要和配置其它 Spring 数据库连接一样配置它就可以了。
      </p>

      
<p>
      假设你定义了一个如下的 mapper 接口：
      </p>
        
<div class="source"><pre class="prettyprint"><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">UserMapper</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="lit">@Select</span><span class="pun">(</span><span class="str">"SELECT * FROM users WHERE id = #{userId}"</span><span class="pun">)</span><span class="pln">
  </span><span class="typ">User</span><span class="pln"> getUser</span><span class="pun">(</span><span class="lit">@Param</span><span class="pun">(</span><span class="str">"userId"</span><span class="pun">)</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> userId</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span><span class="pln"> </span></pre></div>

      
<p>
      那么可以通过 <tt>MapperFactoryBean</tt> 将接口加入到 Spring 中:
      </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userMapper"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.mybatis.spring.mapper.MapperFactoryBean"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"mapperInterface"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"org.mybatis.spring.sample.mapper.UserMapper"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"sqlSessionFactory"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"sqlSessionFactory"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/bean&gt;</span></pre></div>

      
<p>
      需要注意的是：所指定的映射器类<b>必须</b>是一个接口，而不是具体的实现类。在这个示例中，通过注解来指定 SQL 语句，但是也可以使用 MyBatis 映射器的 XML 配置文件。
      </p>

      
<p>
      配置好之后，你就可以像 Spring 中普通的 bean 注入方法那样，将映射器注入到你的业务或服务对象中。<tt>MapperFactoryBean</tt> 将会负责 <tt>SqlSession</tt> 的创建和关闭。如果使用了 Spring 的事务功能，那么当事务完成时，session 将会被提交或回滚。最终任何异常都会被转换成 Spring 的 <tt>DataAccessException</tt> 异常。
      </p>

      
<p>
      使用 Java 代码来配置的方式如下：
      </p>
       
<div class="source"><pre class="prettyprint"><span class="lit">@Bean</span><span class="pln">
</span><span class="kwd">public</span><span class="pln"> </span><span class="typ">UserMapper</span><span class="pln"> userMapper</span><span class="pun">()</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">SqlSessionTemplate</span><span class="pln"> sqlSessionTemplate </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">SqlSessionTemplate</span><span class="pun">(</span><span class="pln">sqlSessionFactory</span><span class="pun">());</span><span class="pln">
  </span><span class="kwd">return</span><span class="pln"> sqlSessionTemplate</span><span class="pun">.</span><span class="pln">getMapper</span><span class="pun">(</span><span class="typ">UserMapper</span><span class="pun">.</span><span class="kwd">class</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span></pre></div>

      
<p>
      要调用 MyBatis 的数据方法，只需一行代码：
      </p>
      
<div class="source"><pre class="prettyprint"><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">FooServiceImpl</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><span class="typ">FooService</span><span class="pln"> </span><span class="pun">{</span><span class="pln">

  </span><span class="kwd">private</span><span class="pln"> </span><span class="kwd">final</span><span class="pln"> </span><span class="typ">UserMapper</span><span class="pln"> userMapper</span><span class="pun">;</span><span class="pln">

  </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">FooServiceImpl</span><span class="pun">(</span><span class="typ">UserMapper</span><span class="pln"> userMapper</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">userMapper </span><span class="pun">=</span><span class="pln"> userMapper</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">

  </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">User</span><span class="pln"> doSomeBusinessStuff</span><span class="pun">(</span><span class="typ">String</span><span class="pln"> userId</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">userMapper</span><span class="pun">.</span><span class="pln">getUser</span><span class="pun">(</span><span class="pln">userId</span><span class="pun">);</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></pre></div>
      </div>
    </div>
  

        </div>
      </div>
    </div>
    <hr>
    <footer>
      <div class="container-fluid">
        <div class="row-fluid">
            <p>Copyright ©2010–2020
<a href="http://www.mybatis.org/">MyBatis.org</a>.
All rights reserved.</p>
        </div>
      </div>
    </footer>
  

<div class="xl-chrome-ext-bar" id="xl_chrome_ext_{4DB361DE-01F7-4376-B494-639E489D19ED}" style="display: none;">
      <div class="xl-chrome-ext-bar__logo"></div>

      <a id="xl_chrome_ext_download" href="javascript:;" class="xl-chrome-ext-bar__option">下载视频</a>
      <a id="xl_chrome_ext_close" href="javascript:;" class="xl-chrome-ext-bar__close"></a>
    </div></body></html>